package com.yls.except.service.impl;

import com.yls.except.dao.*;
import com.yls.except.service.IndentService;
import com.yls.except.task.RedisCash;
import com.yls.except.util.*;
import com.yls.except.util.exception.IndentException;
import com.yls.except.util.kuaidiniao.KdApiOrderDistinguish;
import com.yls.except.util.kuaidiniao.KdniaoTrackQueryAPI;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import wxap.com.utils.GetWxOrderno;
import wxap.com.utils.RequestHandler;
import wxap.com.utils.Sha1Util;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 订单serviceimpl
 * Created by Administrator on 2016/8/13.
 */
@Service
@Repository(value = "indentService")
public class IndentServiceImpl implements IndentService {
    @Resource(name = "indentDao")
    private IndentDao indentDao;
    @Resource(name = "shopDao")
    private ShopDao shopDao;
    @Resource(name = "imgDao")
    private ImgDao imgDao;
    @Resource(name = "systemDao")
    private SystemDao systemDao;
    @Resource(name = "userDao")
    private UserDao userDao;


    @Override
    public Map<String, Object> updatetIndent(String uid, JSONArray shopinfo, String addressid) {
        String pid = "";
        if(!StringIsempty.isallempty(addressid)) {
            Map<String, Object> addressinfo = systemDao.selectAddressInfoById(addressid);
            if (!StringIsempty.isNullMap(addressinfo))
                pid = addressinfo.get("pid") + "";
        }
        Map<String, Object> indentinfo = getIndentInfo(shopinfo, pid, "0", 0, uid);
        indentinfo.put("tag", 1);
        long totalmoney = Long.parseLong(indentinfo.get("totalmoney") + "");
        indentinfo.put("totalmoney", ValueJude.getDecima(indentinfo.get("totalmoney") + ""));
        indentinfo.put("freight", ValueJude.getDecima(indentinfo.get("freight") + ""));
        indentinfo.put("indentmoney", ValueJude.getDecima(indentinfo.get("indentmoney") + ""));
        if (StringIsempty.isallempty(uid)) {
            indentinfo.put("sparemoney", 0);
            indentinfo.put("isenough", false);
        } else {
            Map<String, Object> useraccout = userDao.selectUserAccountByUid(uid);
            if (StringIsempty.isNullMap(useraccout)) {
                indentinfo.put("sparemoney", 0);
                indentinfo.put("isenough", false);
            } else {
                indentinfo.put("sparemoney", ValueJude.getDecima(useraccout.get("sparemoney") + ""));
                long sparemoney = Long.parseLong(useraccout.get("sparemoney") + "");
                if (totalmoney > sparemoney)
                    indentinfo.put("isenough", false);
                else
                    indentinfo.put("isenough", true);
            }
        }
        return indentinfo;
    }

    @Override
    public Map<String, Object> insertIndent(String uid, JSONArray shopinfo, String addressid, String indenttype, String reqip) {
        Map<String, Object> user = userDao.selectUserInfoByUid(uid);
        if(StringIsempty.isNullMap(user))
            return null;
        Map<String, Object> map = new HashMap<String, Object>();
        if("1".equals(indenttype) && "0".equals(user.get("type") + "")) {
            map.put("tag", -62);
            map.put("message", "权限不足");
            return map;
        }
        Map<String, Object> addressinfo = systemDao.selectAddressInfoById(addressid);
        if (StringIsempty.isNullMap(addressinfo) && "0".equals(indenttype)) {
            map.put("tag", -42);
            map.put("message", "该收货地址不存在");
            return map;
        }
        String pid = addressinfo.get("pid") + "";
        Map<String, Object> indentinfo = getIndentInfo(shopinfo, pid, indenttype, 1, uid);
        String indentnum = UtilDate.getOrderNum();
        indentinfo.put("indent_num", indentnum);
        indentinfo.put("uid", uid);
        indentinfo.put("type", indenttype);
        indentinfo.put("typeid", "");
        indentinfo.put("address_id", addressid);
        indentinfo.put("indent_state", 1);
        indentinfo.put("addtime", new Date().getTime());
        indentinfo.put("addip", reqip);
        indentinfo.put("isdisabled", 1);
        indentinfo.put("paytime", 0);
        indentinfo.put("paytype", 0);
        int tag = indentDao.insertIndentInfo(indentinfo);
        if (tag <= 0)
            return null;
        for (int i = 0; i < shopinfo.length(); i++) {
            try {
                String shopid = shopinfo.getJSONObject(i).get("shopid") + "";
                long number = Long.parseLong(shopinfo.getJSONObject(i).get("num") + "");
                String babysex = shopinfo.getJSONObject(i).get("sex") + "";
                String babyageid = shopinfo.getJSONObject(i).get("age") + "";
                String shopspecpriceid = shopinfo.getJSONObject(i).get("shopspecid") + "";
                Map<String, Object> indentshop = new HashMap<String, Object>();
                indentshop.put("indent_shop_id", ValueJude.getUuid());
                indentshop.put("indent_num", indentnum);
                indentshop.put("shop_id", shopid);
                indentshop.put("num", number);
                indentshop.put("baby_sex", babysex);
                indentshop.put("baby_age_id", babyageid);
                indentshop.put("shop_spec_price", shopspecpriceid);
                indentshop.put("addtime", new Date().getTime());
                indentshop.put("addip", reqip);
                indentshop.put("isdisabled", 1);
                indentDao.insertIndentShopInfo(indentshop);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Map<String, Object> account = userDao.selectUserAccountByUid(uid);
        if (StringIsempty.isNullMap(account))
            map.put("sparemoney", 0);
        else
            map.put("sparemoney", ValueJude.getDecima(account.get("sparemoney") + ""));
        map.put("indentnum", indentnum);
        map.put("totalmoney", ValueJude.getDecima(indentinfo.get("totalmoney") + ""));
        map.put("freight", ValueJude.getDecima(indentinfo.get("freight") + ""));
        map.put("tag", 1);
        return map;
    }

    @Override
    public Map<String, Object> updateIndentInfo(String uid, String indentnum, String paytype, String reqip, String openid, String requrl) {
        Map<String, Object> indentinfo = indentDao.selectIndentInfoByIndentNum(indentnum);
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringIsempty.isNullMap(indentinfo))
            return null;
        if (!"1".equals(indentinfo.get("indent_state") + "")) {
            map.put("tag", -45);
            return map;
        }
        int tag;
        long paymoney = Long.parseLong(indentinfo.get("paymoney") + "");
        String prepayid = "";
        int indenttime = (int)(new Date().getTime() / 1000);

        if ("1".equals(paytype) || paymoney == 0) {
            if(paymoney != 0) {
                Map<String, Object> account = userDao.selectUserAccountByUid(uid);
                if (StringIsempty.isNullMap(account) || paymoney > Long.parseLong(account.get("sparemoney") + "")) {
                    map.put("tag", -19);
                    return map;
                }
                account.put("sparemoney", Long.parseLong(account.get("sparemoney") + "") - paymoney);
                tag = userDao.updateUserAccount(account);
                if (tag <= 0)
                    throw new IndentException("修改用户帐户信息失败");
            }
            String type = indentinfo.get("type") + "";
            if ("1".equals(type)) {
                List<Map<String, Object>> indentshop = indentDao.selectIndentShopInfoByIndentNum(indentnum);
                if (!StringIsempty.isNullList(indentshop)) {
                    for (int i = 0; i < indentshop.size(); i++) {
                        Map<String, Object> indentshopinfo = indentshop.get(i);
                        if (StringIsempty.isNullMap(indentshopinfo))
                            continue;
                        Map<String, Object> repertory = new HashMap<String, Object>();
                        repertory.put("uid", uid);
                        repertory.put("shop_id", indentshopinfo.get("shop_id") + "");
                        repertory.put("shop_spec_price", indentshopinfo.get("shop_spec_price") + "");
                        Map<String, Object> repertoryinfo = indentDao.selectReperToryInfoByUidAndShopidAndShopSpecPriceId(repertory);
                        if (StringIsempty.isNullMap(repertoryinfo)) {
                            repertory.put("repertory_id", ValueJude.getUuid());
                            repertory.put("num", indentshopinfo.get("num") + "");
                            repertory.put("isdisabled", 1);
                            repertory.put("sendnum", 0);
                            tag = indentDao.insertRepertory(repertory);
                        } else {
                            repertoryinfo.put("num", Long.parseLong(indentshopinfo.get("num") + "") + Long.parseLong(repertoryinfo.get("num") + ""));
                            repertoryinfo.put("isdisabled", 1);
                            tag = indentDao.updateRepertory(repertoryinfo);
                        }
                        if (tag <= 0)
                            throw new IndentException("新增用户仓储失败");
                    }
                }
            }
            indentinfo.put("indent_state", 2);
            indentinfo.put("paytime", new Date().getTime());
        } else {
            Map<String, Object> paymap = getWeChatPrepayId(indentnum, reqip, paymoney, openid, indenttime, requrl);
            map.put("prepay_id", paymap.get("prepay_id"));
            map.put("result_sign", paymap.get("result_sign"));
            map.put("signbefore", paymap.get("signbefore"));
            map.put("nonce_str", paymap.get("nonceStr"));
            map.put("indenttime", indenttime);
            map.put("sign", paymap.get("sign"));
            System.out.println(map);
//            map.put("signature", paymap.get("signature"));
        }
        indentinfo.put("paytype", paytype);
        tag = indentDao.updateIndentInfo(indentinfo);
        if (tag <= 0)
            throw new IndentException();
        map.put("shopname", "摘记");
        map.put("shopdesc", "购买商品");
        map.put("indentnum", indentnum);
        map.put("tn", prepayid);
        map.put("paymoney", ValueJude.getDecima(paymoney + ""));
        map.put("tag", 1);
        return map;
    }

    @Override
    public List<Object> selectIndentListInfoByUid(String uid, String indentstate, String page, String indenttype) {
        int nowpage = 0;
        if (!StringIsempty.isallempty(page))
            nowpage = Integer.parseInt(page);
        Map<String, Object> map = PageUtil.getNowPage(nowpage);
        map.put("uid", uid);
        if (StringIsempty.isallempty(indentstate) || "0".equals(indentstate))
            map.put("indentstate", "");
        else
            map.put("indentstate", " and indent_state=" + indentstate);
        if (StringIsempty.isallempty(indenttype))
            map.put("type", " and type=0");
        else
            map.put("type", " and type in (" + indenttype + ")");
        List<Object> list = new ArrayList<Object>();
        List<Map<String, Object>> indent = indentDao.selectIndentInfoByUidAndIndentState(map);
        if (!StringIsempty.isNullList(indent)) {
            for (int i = 0; i < indent.size(); i++) {
                Map<String, Object> indentinfo = indent.get(i);
                if (StringIsempty.isNullMap(indentinfo))
                    continue;
                String indentnum = indentinfo.get("indent_num") + "";
                indentinfo.put("money", ValueJude.getDecima(indentinfo.get("money") + ""));
                indentinfo.put("freight_money", ValueJude.getDecima(indentinfo.get("freight_money") + ""));
                indentinfo.put("paymoney", ValueJude.getDecima(indentinfo.get("paymoney") + ""));
                indentinfo.put("favorable", ValueJude.getDecima(indentinfo.get("favorable") + ""));
                String indent_state = indentinfo.get("indent_state") + "";
                indent_state = ValueJude.getIndentStateDesc(indent_state);
                indentinfo.put("indentstatedesc", indent_state);
                List<Map<String, Object>> indentShop = indentDao.selectIndentShopInfoByIndentNum(indentnum);
                if (StringIsempty.isNullList(indentShop))
                    continue;
                getIndentShopInfo(indentShop);
                Map<String, Object> logistics = indentDao.selectLogisticsByIndentNum(indentnum);
                getLogistics(indentinfo, logistics);
                indentinfo.put("indentshop", indentShop);
                list.add(indentinfo);
            }
        }
        return list;
    }

    @Override
    public Map<String, Object> selectIndentInfoById(String indentnum) {
        Map<String, Object> indentinfo = indentDao.selectIndentInfoByIndentNum(indentnum);
        if (StringIsempty.isNullMap(indentinfo))
            return null;
        List<Map<String, Object>> indentShop = indentDao.selectIndentShopInfoByIndentNum(indentnum);
        if (StringIsempty.isNullList(indentShop))
            return null;
        String addressid = indentinfo.get("address_id") + "";
        String uid = indentinfo.get("uid") + "";
        Map<String, Object> account = userDao.selectUserAccountByUid(uid);
        if (StringIsempty.isNullMap(account))
            indentinfo.put("sparemoney", 0);
        else
            indentinfo.put("sparemoney", ValueJude.getDecima(account.get("sparemoney") + ""));
        Map<String, Object> addressinfo = systemDao.selectAddressInfoById(addressid);
        indentinfo.putAll(addressinfo);
        indentinfo.put("money", ValueJude.getDecima(indentinfo.get("money") + ""));
        indentinfo.put("freight_money", ValueJude.getDecima(indentinfo.get("freight_money") + ""));
        indentinfo.put("paymoney", ValueJude.getDecima(indentinfo.get("paymoney") + ""));
        indentinfo.put("favorable", ValueJude.getDecima(indentinfo.get("favorable") + ""));
        String indent_state = indentinfo.get("indent_state") + "";
        indent_state = ValueJude.getIndentStateDesc(indent_state);
        indentinfo.put("indentstatedesc", indent_state);
        getIndentShopInfo(indentShop);
        indentinfo.put("indentshop", indentShop);
        long addtime = Long.parseLong(indentinfo.get("addtime") + "");
        long sendtime = Long.parseLong(indentinfo.get("sendtime") + "");
        long nowtime = new Date().getTime();
        if (nowtime > addtime + 24 * 60 * 60 * 1000)
            indentinfo.put("cancledesc", "已取消");
        else {
            Map<String, Object> cancletime = DateStringLong.getTime(nowtime, addtime + 24 * 60 * 60 * 1000);
            if (StringIsempty.isNullMap(cancletime))
                indentinfo.put("cancledesc", "已取消");
            else
                indentinfo.put("cancledesc", "还剩" + cancletime.get("day") + "天" + cancletime.get("hour") + "时" + cancletime.get("min") + "分自动取消订单");
        }
        if (nowtime > sendtime + 7 * 24 * 60 * 60 * 1000)
            indentinfo.put("recipientdesc", "已确认收货");
        else {
            Map<String, Object> send = DateStringLong.getTime(nowtime, sendtime + 7 * 24 * 60 * 60 * 1000);
            if (StringIsempty.isNullMap(send))
                indentinfo.put("cancledesc", "已取消");
            else
                indentinfo.put("cancledesc", "还剩" + send.get("day") + "天" + send.get("hour") + "时" + send.get("min") + "分自动确认收货");
        }
        Map<String, Object> logistics = indentDao.selectLogisticsByIndentNum(indentnum);
        getLogistics(indentinfo, logistics);
        indentinfo.put("tag", 1);
        return indentinfo;
    }


    @Override
    public int updateCancleIndent(String uid, String indentnum) {
        Map<String, Object> indentinfo = indentDao.selectIndentInfoByIndentNum(indentnum);
        if (StringIsempty.isNullMap(indentinfo))
            return -13;
        if (!uid.equals(indentinfo.get("uid") + ""))
            return -43;
        if (!"1".equals(indentinfo.get("indent_state") + ""))
            return -44;
        indentinfo.put("indent_state", 5);
        return indentDao.updateIndentInfo(indentinfo);
    }

    @Override
    public int insertSendAdvice(String uid, String indentnum, String reqip) {
        Map<String, Object> indentinfo = indentDao.selectIndentInfoByIndentNum(indentnum);
        if (StringIsempty.isNullMap(indentinfo))
            return -13;
        if (!uid.equals(indentinfo.get("uid") + ""))
            return -43;
        if (!"2".equals(indentinfo.get("indent_state") + ""))
            return -44;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("indentnum", indentnum);
        map.put("uid", uid);
        Map<String, Object> sendadvice = indentDao.selectSendAdviceInfoByIndentNumAndUid(map);
        if (StringIsempty.isNullMap(sendadvice)) {
            map.put("addtime", new Date().getTime());
            map.put("addip", reqip);
            map.put("isdisabled", 1);
            return indentDao.insertSendAdvice(map);
        } else {
            long addtime = Long.parseLong(sendadvice.get("addtime") + "");
            long nowtime = new Date().getTime();
            if (nowtime > addtime + 360000) {
                sendadvice.put("addtime", new Date().getTime());
                sendadvice.put("addip", reqip);
                sendadvice.put("isdisabled", 1);
                return indentDao.updateSendAdvice(sendadvice);
            }
        }
        return 1;
    }

    @Override
    public int updateConfirmIndent(String uid, String indentnum, String reqip) {
        Map<String, Object> indentinfo = indentDao.selectIndentInfoByIndentNum(indentnum);
        if (StringIsempty.isNullMap(indentinfo))
            return -13;
        if (!uid.equals(indentinfo.get("uid") + ""))
            return -43;
        if (!"3".equals(indentinfo.get("indent_state") + ""))
            return -44;
        Map<String, Object> invite = userDao.selectInviteInfoByUid(uid);
        if (!StringIsempty.isNullMap(invite)) {
            String inviteuid = invite.get("invite_uid") + "";
            Map<String, Object> useraccout = userDao.selectUserAccountByUid(inviteuid);
            long proxyrate;
            Map<String, Object> proxyUser = systemDao.selectProxyUserRateByUid(uid);
            if (!StringIsempty.isNullMap(proxyUser))
                proxyrate = Long.parseLong(proxyUser.get("rate") + "");
            else {
                Map<String, Object> systemset = systemDao.selectSystemSetInfoById("2");
                if (StringIsempty.isNullMap(systemset))
                    proxyrate = 1000;
                else
                    proxyrate = Long.parseLong(systemset.get("content") + "");
            }
            long paymoney = Long.parseLong(indentinfo.get("paymoney") + "");
            long ratemoney = paymoney * proxyrate / 10000;
            if (StringIsempty.isNullMap(useraccout)) {
                useraccout = new HashMap<String, Object>();
                useraccout.put("account_num", ValueJude.getUuid());
                useraccout.put("uid", inviteuid);
                useraccout.put("sparemoney", ratemoney);
                useraccout.put("paypwd", "");
                useraccout.put("addtime", new Date().getTime());
                useraccout.put("addip", reqip);
                useraccout.put("isdisabled", 1);
                int tag = userDao.insertUserAccount(useraccout);
                if (tag <= 0)
                    throw new IndentException();
            } else {
                useraccout.put("sparemoney", Long.parseLong(useraccout.get("sparemoney") + "") + ratemoney);
                int tag = userDao.updateUserAccount(useraccout);
                if (tag <= 0)
                    throw new IndentException();
            }
            Map<String, Object> invitemoney = new HashMap<String, Object>();
            invitemoney.put("invite_money_id", ValueJude.getUuid());
            invitemoney.put("indent_num", indentnum);
            invitemoney.put("indent_uid", uid);
            invitemoney.put("uid", inviteuid);
            invitemoney.put("indent_money", paymoney);
            invitemoney.put("percentage", ratemoney);
            invitemoney.put("addtime", new Date().getTime());
            invitemoney.put("addip", reqip);
            invitemoney.put("isdisabled", 1);
            int tag = systemDao.insertInviteMoney(invitemoney);
            if (tag <= 0)
                throw new IndentException();
        }
        indentinfo.put("indent_state", 4);
        indentinfo.put("recipienttime", new Date().getTime());
        return indentDao.updateIndentInfo(indentinfo);
    }

    @Override
    public List<Object> selectShopIndetByUid(String uid, String page) {
        Map<String, Object> user = userDao.selectUserInfoByUid(uid);
        if(StringIsempty.isNullMap(user))
            return null;
        if("0".equals(user.get("type") + ""))
            return null;
        int nowpage = 0;
        if (!StringIsempty.isallempty(page))
            nowpage = Integer.parseInt(page);
        Map<String, Object> map = PageUtil.getNowPage(nowpage);
        map.put("uid", uid);
        List<Map<String, Object>> indentshop = indentDao.selectRepertoryInfoByUid(map);
        List<Object> list = new ArrayList<Object>();
        if (!StringIsempty.isNullList(indentshop)) {
            for (int j = 0; j < indentshop.size(); j++) {
                Map<String, Object> indentshopinfo = indentshop.get(j);
                if (StringIsempty.isNullMap(indentshopinfo))
                    continue;
                indentshopinfo.put("price", ValueJude.getDecima(indentshopinfo.get("price") + ""));
                long sendnum = Long.parseLong(indentshopinfo.get("sendnum") + "");
                long num = Long.parseLong(indentshopinfo.get("num") + "");
                indentshopinfo.put("surplusnum", num - sendnum);
                indentshop.set(j, indentshopinfo);
            }
        }

        list.addAll(indentshop);
        return list;
    }

    @Override
    public Map<String, Object> selectRepertoryInfoById(String repertoryid, String uid) {
        Map<String, Object> user = userDao.selectUserInfoByUid(uid);
        if(StringIsempty.isNullMap(user))
            return null;
        Map<String, Object> map = new HashMap<String, Object>();
        if("0".equals(user.get("type") + "")) {
            map.put("tag", -62);
            map.put("message", "权限不足");
            return map;
        }

        Map<String, Object> repertoryinfo = indentDao.selectReperToryInfoById(repertoryid);
        if (StringIsempty.isNullMap(repertoryinfo))
            return null;
        repertoryinfo.put("price", ValueJude.getDecima(repertoryinfo.get("price") + ""));
        long sendnum = Long.parseLong(repertoryinfo.get("sendnum") + "");
        long num = Long.parseLong(repertoryinfo.get("num") + "");
        repertoryinfo.put("surplusnum", num - sendnum);
        repertoryinfo.put("tag", 1);
        return repertoryinfo;
    }

    @Override
    public Map<String, Object> insertBuyVip(String uid, String paytype, String reqip, String openid, String requrl) {
        Map<String, Object> systemset = systemDao.selectSystemSetInfoById("1");
        Map<String, Object> userinfo = userDao.selectUserInfoByUid(uid);
        if (StringIsempty.isNullMap(userinfo))
            return null;
        Map<String, Object> map = new HashMap<String, Object>();
        if ("1".equals(userinfo.get("type") + "")) {
            map.put("tag", -63);
            return map;
        }
        String vipmoney = "99";
        if (!StringIsempty.isNullMap(systemset))
            vipmoney = systemset.get("setvalue") + "";
        int tag;
        Long paymoney = Long.parseLong(vipmoney) * 100;
        Map<String, Object> indentinfo = new HashMap<String, Object>();
        String prepayid = "";
        String indentnum = UtilDate.getOrderNum();
        int indenttime = (int)(new Date().getTime() / 1000);
        if(paymoney == 0) {
            indentinfo.put("indent_state", 2);
            indentinfo.put("paytime", new Date().getTime());
        } else if ("1".equals(paytype)) {
            Map<String, Object> account = userDao.selectUserAccountByUid(uid);
            if (StringIsempty.isNullMap(account) || paymoney > Long.parseLong(account.get("sparemoney") + "")) {
                map.put("tag", -19);
                return map;
            }
            account.put("sparemoney", Long.parseLong(account.get("sparemoney") + "") - paymoney);
            tag = userDao.updateUserAccount(account);
            if (tag <= 0)
                throw new IndentException("修改用户帐户信息失败");
            userinfo.put("type", 2);
            tag = userDao.updateUserInfo(userinfo);
            if (tag <= 0)
                throw new IndentException("修改用户信息失败");
            indentinfo.put("indent_state", 2);
            indentinfo.put("paytime", new Date().getTime());
        } else {
            Map<String, Object> paymap = getWeChatPrepayId(indentnum, reqip, paymoney, openid, indenttime, requrl);
            map.put("prepay_id", paymap.get("prepay_id"));
            map.put("result_sign", paymap.get("result_sign"));
            map.put("signbefore", paymap.get("signbefore"));
            map.put("nonce_str", paymap.get("nonceStr"));
            map.put("indenttime", indenttime);
            map.put("sign", paymap.get("sign"));

            indentinfo.put("indent_state", 1);
            indentinfo.put("paytime", 0);
        }
        indentinfo.put("indent_num", indentnum);
        indentinfo.put("paytype", paytype);
        indentinfo.put("uid", uid);
        indentinfo.put("type", 2);
        indentinfo.put("typeid", "");
        indentinfo.put("address_id", "");
        indentinfo.put("addtime", new Date().getTime());
        indentinfo.put("addip", reqip);
        indentinfo.put("isdisabled", 1);
        indentinfo.put("indentmoney", paymoney);
        indentinfo.put("totalmoney", paymoney);
        indentinfo.put("freight", 0);
        indentinfo.put("favorable", 0);
        tag = indentDao.insertIndentInfo(indentinfo);
        if (tag <= 0)
            throw new IndentException();
        map.put("shopname", "摘记");
        map.put("shopdesc", "购买vip");
        map.put("indentnum", indentnum);
        map.put("tn", prepayid);
        map.put("paymoney", ValueJude.getDecima(paymoney + ""));
        map.put("tag", 1);
        return map;
    }

    @Override
    public Map<String, Object> insertRepertoryIndent(String uid, JSONArray addressids, JSONArray shopinfo, String reqip) {
        Map<String, Object> map = new HashMap<String, Object>();

        Map<String, Object> user = userDao.selectUserInfoByUid(uid);
        if(StringIsempty.isNullMap(user))
            return null;
        if("0".equals(user.get("type") + "")) {
            map.put("tag", -62);
            map.put("message", "权限不足");
            return map;
        }

        //判断仓储商品是否足够
        for (int i = 0; i < shopinfo.length(); i++) {
            try {
                String repertoryid = shopinfo.getJSONObject(i).get("repertoryid") + "";
                long number = Long.parseLong(shopinfo.getJSONObject(i).get("num") + "");
//                String babysex = shopinfo.getJSONObject(i).get("babysex") + "";
//                String babyageid = shopinfo.getJSONObject(i).get("babyageid") + "";
//                String shopspecpriceid = shopinfo.getJSONObject(i).get("shopspecpriceid") + "";
                Map<String, Object> repertoryinfo = indentDao.selectReperToryInfoById(repertoryid);
                if (StringIsempty.isNullMap(repertoryinfo)) {
                    map.put("tag", -64);
                    map.put("message", "商品仓储信息不存在");
                    return map;
                } else {
                    long totalnum = Long.parseLong(repertoryinfo.get("num") + "");
                    long sendnum = Long.parseLong(repertoryinfo.get("sendnum") + "");
                    if (totalnum - sendnum < number * addressids.length()) {
                        map.put("tag", -65);
                        map.put("message", "商品【" + repertoryinfo.get("shop_name") + "】仓储不足");
                        return map;
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        String typeid = ValueJude.getUuid();
        List<Map<String, Object>> indent = new ArrayList<Map<String, Object>>();
        long totalfreight = 0;
        //计算运费，并生成订单
        for (int i = 0; i < addressids.length(); i++) {
            try {
                String addressid = addressids.get(i) + "";
                Map<String, Object> address = systemDao.selectAddressInfoById(addressid);
                if (StringIsempty.isNullMap(address) || !uid.equals(address.get("uid") + "")) {
                    map.put("tag", -13);
                    map.put("message", "收货地址有误，请检查");
                    return map;
                }
                SystemServiceImpl.getAddress(address, systemDao);
                String pid = address.get("pid") + "";
                Map<String, Object> indentinfo = getIndentInfo(shopinfo, pid, "0", 1, uid);
                String indentnum = UtilDate.getOrderNum();
                long freight = Long.parseLong(indentinfo.get("freight") + "");
                totalfreight += freight;
                indentinfo.put("indent_num", indentnum);
                indentinfo.put("indentmoney", indentinfo.get("freight") + "");
                indentinfo.put("totalmoney", indentinfo.get("freight") + "");
                indentinfo.put("favorable", 0);
                indentinfo.put("uid", uid);
                indentinfo.put("type", 3);
                indentinfo.put("typeid", typeid);
                indentinfo.put("address_id", addressid);
                indentinfo.put("indent_state", 1);
                indentinfo.put("addtime", new Date().getTime());
                indentinfo.put("addip", reqip);
                indentinfo.put("isdisabled", 1);
                indentinfo.put("paytime", 0);
                indentinfo.put("paytype", 0);
                int tag = indentDao.insertIndentInfo(indentinfo);
                if (tag <= 0)
                    return null;
                List<Map<String, Object>> repertory = new ArrayList<Map<String, Object>>();
                for (int j = 0; j < shopinfo.length(); j++) {
                    try {
                        String shopid = shopinfo.getJSONObject(j).get("shopid") + "";
                        long number = Long.parseLong(shopinfo.getJSONObject(j).get("num") + "");
                        String shopspecpriceid = shopinfo.getJSONObject(j).get("shopspecid") + "";
                        String repertoryid = shopinfo.getJSONObject(j).get("repertoryid") + "";
                        Map<String, Object> repertoryinfo = indentDao.selectReperToryInfoById(repertoryid);
                        Map<String, Object> indentshop = new HashMap<String, Object>();
                        indentshop.put("indent_shop_id", ValueJude.getUuid());
                        indentshop.put("indent_num", indentnum);
                        indentshop.put("shop_id", shopid);
                        indentshop.put("num", number);
                        indentshop.put("baby_sex", 0);
                        indentshop.put("baby_age_id", 0);
                        indentshop.put("shop_spec_price", shopspecpriceid);
                        indentshop.put("addtime", new Date().getTime());
                        indentshop.put("addip", reqip);
                        indentshop.put("isdisabled", 1);
                        indentDao.insertIndentShopInfo(indentshop);
                        repertoryinfo.put("indentnum", indentnum);
                        repertoryinfo.put("sendnum", Long.parseLong(repertoryinfo.get("sendnum") + "") + number);
                        indentDao.updateRepertorySend(repertoryinfo);  //修改仓储信息
                        repertoryinfo.put("price", ValueJude.getDecima(repertoryinfo.get("price") + ""));
                        repertoryinfo.put("chosenum", number);
                        repertory.add(repertoryinfo);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                address.put("indentnum", indentnum);
                address.put("freight", ValueJude.getDecima(freight + ""));
                address.put("repertory", repertory);
                indent.add(address);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Map<String, Object> useraccount = userDao.selectUserAccountByUid(uid);
        if (StringIsempty.isNullMap(useraccount)) {
            map.put("sparemoney", 0);
            map.put("isenough", false);
        } else {
            long sparemoney = Long.parseLong(useraccount.get("sparemoney") + "");
            map.put("sparemoney", ValueJude.getDecima(useraccount.get("sparemoney") + ""));
            if (totalfreight > sparemoney)
                map.put("isenough", false);
            else
                map.put("isenough", true);
        }
        map.put("indent", indent);
        map.put("totalfreight", ValueJude.getDecima(totalfreight + ""));   //总运费
        map.put("typeid", typeid);
        map.put("tag", 1);
        return map;
    }

    @Override
    public Map<String, Object> updateRepertoryPay(String uid, String typeid, String paytype, String reqip, String openid, String requrl) {
        List<Map<String, Object>> indentinfo = indentDao.selectIndentInfoByTypeId(typeid);
        Map<String, Object> map = new HashMap<String, Object>();

        Map<String, Object> user = userDao.selectUserInfoByUid(uid);
        if(StringIsempty.isNullMap(user))
            return null;
        if("0".equals(user.get("type") + "")) {
            map.put("tag", -62);
            map.put("message", "权限不足");
            return map;
        }

        if (StringIsempty.isNullList(indentinfo)) {
            map.put("tag", -13);
            map.put("message", "该订单信息不存在");
            return map;
        }
        long money = 0;
        for (int i = 0; i < indentinfo.size(); i++) {
            Map<String, Object> indent = indentinfo.get(i);
            if (StringIsempty.isNullMap(indent))
                continue;
            long paymoney = Long.parseLong(indent.get("paymoney") + "");
            money += paymoney;
        }
        String prepayid = "";
        int indenttime = (int)(new Date().getTime() / 1000);
        Map<String, Object> indent = new HashMap<String, Object>();

        if(money == 0){
            indent.put("indent_state", 2);
            indent.put("paytime", new Date().getTime());
        }else if ("1".equals(paytype)) {
            Map<String, Object> account = userDao.selectUserAccountByUid(uid);
            if ((StringIsempty.isNullMap(account) || money > Long.parseLong(account.get("sparemoney") + "")) && money != 0) {
                map.put("tag", -19);
                return map;
            }
            account.put("sparemoney", Long.parseLong(account.get("sparemoney") + "") - money);
            int tag = userDao.updateUserAccount(account);
            if (tag <= 0)
                throw new IndentException("修改用户帐户信息失败");
            indent.put("indent_state", 2);
            indent.put("paytime", new Date().getTime());
        } else {
            indent.put("indent_state", 1);
            indent.put("paytime", 0);
            Map<String, Object> paymap = getWeChatPrepayId(typeid, reqip, money, openid, indenttime, requrl);
            map.put("prepay_id", paymap.get("prepay_id"));
            map.put("result_sign", paymap.get("result_sign"));
            map.put("signbefore", paymap.get("signbefore"));
            map.put("nonce_str", paymap.get("nonceStr"));
            map.put("indenttime", indenttime);
            map.put("sign", paymap.get("sign"));
        }
        indent.put("paytype", paytype);
        indent.put("typeid", typeid);
        indent.put("return_num", "");
        int tag = indentDao.updateRepertoryIndentInfo(indent);
        if (tag <= 0)
            throw new IndentException();
        map.put("shopname", "摘记");
        map.put("shopdesc", "仓储发货");
        map.put("indentnum", typeid);
        map.put("tn", prepayid);
        map.put("paymoney", ValueJude.getDecima(money + ""));
        map.put("tag", 1);
        return map;
    }

    @Override
    public int deleteIndent(String uid, String indentnum) {
        Map<String, Object> indentinfo = indentDao.selectIndentInfoByIndentNum(indentnum);
        if (StringIsempty.isNullMap(indentinfo))
            return -13;
        if (!uid.equals(indentinfo.get("uid") + ""))
            return -43;
        if (!"4".equals(indentinfo.get("indent_state") + "") && !"5".equals(indentinfo.get("indent_state") + ""))
            return -44;
        indentinfo.put("isdisabled", 0);
        return indentDao.updateIndentInfo(indentinfo);
    }

    @Override
    public List<Object> selectRepertoryIndent(String uid, String indentstate, String page) {
        int nowpage = 0;
        if (!StringIsempty.isallempty(page))
            nowpage = Integer.parseInt(page);
        Map<String, Object> map = PageUtil.getNowPage(nowpage);
        map.put("uid", uid);
        if (StringIsempty.isallempty(indentstate) || "0".equals(indentstate))
            map.put("indentstate", " and indent_state=1");
        else
            map.put("indentstate", " and indent_state in (" + indentstate + ")");
        map.put("type", " and type=" + 1);
        List<Object> list = new ArrayList<Object>();
        List<Map<String, Object>> indent = indentDao.selectRepertoryIndentInfoByUidAndIndentState(map);
        if (!StringIsempty.isNullList(indent)) {
            for (int i = 0; i < indent.size(); i++) {
                Map<String, Object> indentinfo = indent.get(i);
                if (StringIsempty.isNullMap(indentinfo))
                    continue;
//                Map<String, Object> repertoryinfo = repertoryindent.get(j);
                if (StringIsempty.isNullMap(indentinfo))
                    continue;
                indentinfo.put("money", ValueJude.getDecima(indentinfo.get("money") + ""));
                String indentnum = indentinfo.get("indent_num") + "";
                indentinfo.put("freight_money", ValueJude.getDecima(indentinfo.get("freight_money") + ""));
                indentinfo.put("paymoney", ValueJude.getDecima(indentinfo.get("paymoney") + ""));
                indentinfo.put("favorable", ValueJude.getDecima(indentinfo.get("favorable") + ""));
                String indent_state = indentinfo.get("indent_state") + "";
                indent_state = ValueJude.getIndentStateDesc(indent_state);
                indentinfo.put("indentstatedesc", indent_state);
                List<Map<String, Object>> indentShop = indentDao.selectIndentShopInfoByIndentNum(indentnum);
                if (StringIsempty.isNullList(indentShop))
                    continue;
                getIndentShopInfo(indentShop);
                Map<String, Object> logistics = indentDao.selectLogisticsByIndentNum(indentnum);
                getLogistics(indentinfo, logistics);
                indentinfo.put("indentshop", indentShop);
//                repertoryindent.set(j, repertoryinfo);

//                String typeid = indentinfo.get("typeid") + "";
//                List<Map<String, Object>> repertoryindent = indentDao.selectRepertoryIndentInfoByTypeid(typeid);
//                if(!StringIsempty.isNullList(repertoryindent)) {
//                    for (int j = 0; j < repertoryindent.size(); j ++) {
//                        Map<String, Object> repertoryinfo = repertoryindent.get(j);
//                        if(StringIsempty.isNullMap(repertoryinfo))
//                            continue;
//                        repertoryinfo.put("money", ValueJude.getDecima(indentinfo.get("money") + ""));
//                        String indentnum = repertoryinfo.get("indent_num") + "";
//                        repertoryinfo.put("freight_money", ValueJude.getDecima(repertoryinfo.get("freight_money") + ""));
//                        repertoryinfo.put("paymoney", ValueJude.getDecima(repertoryinfo.get("paymoney") + ""));
//                        repertoryinfo.put("favorable", ValueJude.getDecima(repertoryinfo.get("favorable") + ""));
//                        String indent_state = repertoryinfo.get("indent_state") + "";
//                        indent_state = ValueJude.getIndentStateDesc(indent_state);
//                        repertoryinfo.put("indentstatedesc", indent_state);
//                        List<Map<String, Object>> indentShop = indentDao.selectIndentShopInfoByIndentNum(indentnum);
//                        if (StringIsempty.isNullList(indentShop))
//                            continue;
//                        getIndentShopInfo(indentShop);
//                        Map<String, Object> logistics = indentDao.selectLogisticsByIndentNum(indentnum);
//                        getLogistics(indentinfo, logistics);
//                        repertoryinfo.put("indentshop", indentShop);
//                        repertoryindent.set(j, repertoryinfo);
//                    }
//                }
//                indentinfo.put("indentinfo", repertoryindent);
                list.add(indentinfo);
            }
        }
        return list;
    }

    @Override
    public void updatePayReturn(String indentnum, String totalfee, int type, String returnnum, HttpServletResponse resp) {
        Map<String, Object> indentinfo = indentDao.selectIndentInfoByIndentNum(indentnum);
        List<Map<String, Object>> repertoryindent = indentDao.selectIndentInfoByTypeId(indentnum);
        if(StringIsempty.isNullMap(indentinfo) && StringIsempty.isNullList(repertoryindent))
            return;
        if(!StringIsempty.isNullMap(indentinfo)) {
            if(!"1".equals(indentinfo.get("indent_state") + ""))
                return;
            if(!totalfee.equals(indentinfo.get("paymoney") + ""))
                indentinfo.put("indent_state", 6);
            else {
                String indenttype = indentinfo.get("type") + "";
                indentinfo.put("paytime", new Date().getTime());
                indentinfo.put("return_num", returnnum);
                    indentinfo.put("indent_state", 2);
                String uid = indentinfo.get("uid") + "";
                Map<String, Object> user = userDao.selectUserInfoByUid(uid);
                if("0".equals(indenttype)) {  //订单类型（0：物流   1:仓储  2：购买vip 3：仓储发货 4:余额充值）
                } else if("1".equals(indenttype)) {
                    List<Map<String, Object>> indentshop = indentDao.selectIndentShopInfoByIndentNum(indentnum);
                    if(!StringIsempty.isNullList(indentshop)) {
                        for (int i = 0; i < indentshop.size(); i ++) {
                            Map<String, Object> indentshopinfo = indentshop.get(i);
                            Map<String, Object> repertory = new HashMap<String, Object>();
                            repertory.put("uid", uid);
                            repertory.put("shop_id", indentshopinfo.get("shop_id") + "");
                            repertory.put("shop_spec_price", indentshopinfo.get("shop_spec_price") + "");
                            Map<String, Object> repertoryinfo = indentDao.selectReperToryInfoByUidAndShopidAndShopSpecPriceId(repertory);
                            if (StringIsempty.isNullMap(repertoryinfo)) {
                                repertory.put("repertory_id", ValueJude.getUuid());
                                repertory.put("num", indentshopinfo.get("num") + "");
                                repertory.put("isdisabled", 1);
                                repertory.put("sendnum", 0);
                                indentDao.insertRepertory(repertory);
                            } else {
                                repertoryinfo.put("num", Long.parseLong(indentshopinfo.get("num") + "") + Long.parseLong(repertoryinfo.get("num") + ""));
                                repertoryinfo.put("isdisabled", 1);
                                indentDao.updateRepertory(repertoryinfo);
                            }
                        }
                    }
                } else if("4".equals(indenttype)) {
                    String typeid = indentinfo.get("typeid") + "";
                    if(Integer.parseInt(user.get("type") + "") < Integer.parseInt(typeid) - 1){
                        user.put("type", Integer.parseInt(typeid) - 1);
                        userDao.updateUserInfo(user);
                    }
                    Map<String, Object> useraccount = userDao.selectUserAccountByUid(uid);
                    if(StringIsempty.isNullMap(useraccount)) {
                        useraccount = new HashMap<String, Object>();
                        useraccount.put("account_num", ValueJude.getUuid());
                        useraccount.put("uid", uid);
                        useraccount.put("sparemoney", totalfee);
                        useraccount.put("paypwd", "");
                        useraccount.put("addtime", new Date().getTime());
                        useraccount.put("addip", "");
                        useraccount.put("isdisabled", 1);
                        int tag = userDao.insertUserAccount(useraccount);
                    } else {
                        useraccount.put("sparemoney", Long.parseLong(totalfee) + Long.parseLong(useraccount.get("sparemoney") + ""));
                        int tag = userDao.updateUserAccount(useraccount);
                    }
                } else {
                    if(!StringIsempty.isNullMap(user)) {
                        user.put("type", 1);
                        userDao.updateUserInfo(user);
                    }

                    String item = ImgProperties.getConstan("itemname");
                    Cookie namecookie = new Cookie("type", "1");
                    namecookie.setMaxAge(-1);
                    namecookie.setPath("/" + item);
                    resp.addCookie(namecookie);
                }
            }
            indentDao.updateIndentInfo(indentinfo);
        } else {
            Map<String, Object> indent = new HashMap<String, Object>();
            indent.put("indent_state", 2);
            indent.put("paytime", new Date().getTime());
            indent.put("paytype", 2);
            indent.put("return_num", returnnum);
            indent.put("typeid", indentnum);
            indentDao.updateRepertoryIndentInfo(indent);
        }
    }

    @Override
    public int updateRepertoryCancle(String uid, String indentnum) {
        Map<String, Object> indentinfo = indentDao.selectIndentInfoByIndentNum(indentnum);
        if(StringIsempty.isNullMap(indentinfo))
            return -13;
        if (!uid.equals(indentinfo.get("uid") + ""))
            return -43;
        if (!"1".equals(indentinfo.get("indent_state") + ""))
            return -44;
        indentinfo.put("indent_state", 5);
        int tag = indentDao.updateIndentInfo(indentinfo);
        if(tag <= 0)
            return 0;
        List<Map<String, Object>> indentshop = indentDao.selectIndentShopInfoByIndentNum(indentnum);
        if(!StringIsempty.isNullList(indentshop)) {
            for (int i = 0; i < indentshop.size(); i ++) {
                Map<String, Object> indentshopinfo = indentshop.get(i);
                if(!StringIsempty.isNullMap(indentshopinfo)) {
                    Map<String, Object> repertory = new HashMap<String, Object>();
                    repertory.put("uid", uid);
                    repertory.put("shop_id", indentshopinfo.get("shop_id") + "");
                    repertory.put("shop_spec_price", indentshopinfo.get("shop_spec_price") + "");
                    Map<String, Object> repertoryinfo = indentDao.selectReperToryInfoByUidAndShopidAndShopSpecPriceId(repertory);
                    if(!StringIsempty.isNullMap(repertoryinfo)) {
                        repertoryinfo.put("sendnum", Long.parseLong(repertoryinfo.get("sendnum") + "") - Long.parseLong(indentshopinfo.get("num") + ""));
                        repertoryinfo.put("isdisabled", 1);
                        indentDao.updateRepertory(repertoryinfo);
                    }
                }
            }
        }
        return tag;
    }

    @Override
    public Map<String, Object> selectUserinfoById(String uid) {
        Map<String, Object> useraccount = userDao.selectUserAccountByUid(uid);
        return useraccount;
    }

    @Override
    public Map<String, Object> updateRepertorySinglePay(String indentnum, String uid, String paytype, String reqip, String openid) {
        Map<String, Object> indentinfo = indentDao.selectIndentInfoByIndentNum(indentnum);
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringIsempty.isNullMap(indentinfo))
            return null;
        if (!"1".equals(indentinfo.get("indent_state") + "")) {
            map.put("tag", -45);
            return map;
        }
        int tag;
        long paymoney = Long.parseLong(indentinfo.get("paymoney") + "");
        String prepayid = "";
        int indenttime = (int)(new Date().getTime() / 1000);
        if(paymoney == 0) {
            indentinfo.put("indent_state", 2);
            indentinfo.put("paytime", new Date().getTime());
        } else if ("1".equals(paytype)) {
            Map<String, Object> account = userDao.selectUserAccountByUid(uid);
            if (StringIsempty.isNullMap(account) || paymoney > Long.parseLong(account.get("sparemoney") + "")) {
                map.put("tag", -19);
                return map;
            }
            account.put("sparemoney", Long.parseLong(account.get("sparemoney") + "") - paymoney);
            tag = userDao.updateUserAccount(account);
            if (tag <= 0)
                throw new IndentException("修改用户帐户信息失败");

            indentinfo.put("indent_state", 2);
            indentinfo.put("paytime", new Date().getTime());
        } else {
            Map<String, Object> paymap = getWeChatPrepayId(indentnum, reqip, paymoney, openid, indenttime, "");
            map.put("prepay_id", paymap.get("prepay_id"));
            map.put("result_sign", paymap.get("result_sign"));
            map.put("signbefore", paymap.get("signbefore"));
            map.put("nonce_str", paymap.get("nonceStr"));
            map.put("indenttime", indenttime);
            map.put("sign", paymap.get("sign"));
        }
        indentinfo.put("paytype", paytype);
        tag = indentDao.updateIndentInfo(indentinfo);
        if (tag <= 0)
            throw new IndentException();
        map.put("shopname", "摘记");
        map.put("shopdesc", "仓储发货");
        map.put("indentnum", indentnum);
        map.put("tn", prepayid);
        map.put("paymoney", ValueJude.getDecima(paymoney + ""));
        map.put("tag", 1);
        return map;
    }

    @Override
    public Map<String, Object> insertRecharge(String uid, String paytype, String bntid, String openid, String reqip) {
        String systemsetid = "";
        if("firstmoney".equals(bntid))
            systemsetid = "3";
        else if("secondmoney".equals(bntid))
            systemsetid = "4";
        else if("thirdmoney".equals(bntid))
            systemsetid = "5";
        else if("forthmoney".equals(bntid))
            systemsetid = "6";
        else
            return null;
        Map<String, Object> systemset = systemDao.selectSystemSetInfoById(systemsetid);
        Map<String, Object> userinfo = userDao.selectUserInfoByUid(uid);
        if (StringIsempty.isNullMap(userinfo))
            return null;
        Map<String, Object> map = new HashMap<String, Object>();

        String rechargemoney = "500";
        if (!StringIsempty.isNullMap(systemset))
            rechargemoney = systemset.get("setvalue") + "";
        int tag;
        Long paymoney = Long.parseLong(rechargemoney) * 100;
        Map<String, Object> indentinfo = new HashMap<String, Object>();
        String prepayid = "";
        String indentnum = UtilDate.getOrderNum();
        int indenttime = (int)(new Date().getTime() / 1000);
        if(paymoney == 0) {
            indentinfo.put("indent_state", 2);
            indentinfo.put("paytime", new Date().getTime());
        }else {
            Map<String, Object> paymap = getWeChatPrepayId(indentnum, reqip, paymoney, openid, indenttime, "");
            map.put("prepay_id", paymap.get("prepay_id"));
            map.put("result_sign", paymap.get("result_sign"));
            map.put("signbefore", paymap.get("signbefore"));
            map.put("nonce_str", paymap.get("nonceStr"));
            map.put("indenttime", indenttime);
            map.put("sign", paymap.get("sign"));

            indentinfo.put("indent_state", 1);
            indentinfo.put("paytime", 0);
        }
        indentinfo.put("indent_num", indentnum);
        indentinfo.put("paytype", paytype);
        indentinfo.put("uid", uid);
        indentinfo.put("type", 4);
        indentinfo.put("typeid", systemsetid);
        indentinfo.put("address_id", "");
        indentinfo.put("addtime", new Date().getTime());
        indentinfo.put("addip", reqip);
        indentinfo.put("isdisabled", 1);
        indentinfo.put("indentmoney", paymoney);
        indentinfo.put("totalmoney", paymoney);
        indentinfo.put("freight", 0);
        indentinfo.put("favorable", 0);
        tag = indentDao.insertIndentInfo(indentinfo);
        if (tag <= 0)
            throw new IndentException();
        map.put("shopname", "摘记");
        map.put("shopdesc", "购买vip");
        map.put("indentnum", indentnum);
        map.put("tn", prepayid);
        map.put("paymoney", ValueJude.getDecima(paymoney + ""));
        map.put("tag", 1);
        return map;
    }

    @Override
    public Map<String, Object> selectLogisticInfo(String indentnum) {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> logistic = indentDao.selectLogisticsByIndentNum(indentnum);
        String logistics_num = "";
        if(!StringIsempty.isNullMap(logistic)) {
            logistics_num = logistic.get("logistics_num") + "";
            String result = KdApiOrderDistinguish.getOrderTracesByJson(logistics_num);
            if(!StringIsempty.isallempty(result)) {
                Map<String, Object> resultMap = GeneralResult.jsonStrToMap(result);
                if(!StringIsempty.isNullMap(resultMap)) {
                    JSONArray jsonArray = (JSONArray) resultMap.get("Shippers");
                    try {
                        if(jsonArray != null && jsonArray.length() > 0) {
                            String ShipperCode = ((JSONObject)jsonArray.get(0)).get("ShipperCode") + "";
                            String ShipperName = ((JSONObject)jsonArray.get(0)).get("ShipperName") + "";
                            map.put("ShipperName", ShipperName);
                            map.put("logisticsnum", logistics_num);
                            result = KdniaoTrackQueryAPI.getOrderTracesByJson(ShipperCode, logistics_num);
                            if(!StringIsempty.isallempty(result)) {
                                resultMap = GeneralResult.jsonStrToMap(result);
                                if(!StringIsempty.isNullMap(resultMap)) {
                                    jsonArray = (JSONArray) resultMap.get("Traces");
                                    if(jsonArray != null && jsonArray.length() > 0) {
                                        List<Object> list = new ArrayList<Object>();
                                        for (int i = jsonArray.length() - 1; i >= 0; i --) {
                                            JSONObject jsonObject = (JSONObject) jsonArray.get(i);

                                            Map<String, Object> accept = new HashMap<String, Object>();
                                            accept.put("AcceptTime", jsonObject.getString("AcceptTime"));
                                            accept.put("AcceptStation", jsonObject.getString("AcceptStation"));
                                            list.add(accept);
                                        }
                                        map.put("traces", list);
                                        map.put("length", jsonArray.length());
                                    } else {
                                        map.put("traces", "");
                                        map.put("length", 0);
                                    }
                                    String State = resultMap.get("State") + "";
                                    map.put("State", State);
                                    if("2".equals(State))
                                        map.put("statedesc", "运送中");
                                    else if("3".equals(State))
                                        map.put("statedesc", "已签收");
                                    else
                                        map.put("statedesc", "暂无信息");
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        List<Map<String, Object>> indentshop = indentDao.selectIndentShopInfoByIndentNum(indentnum);
        if(StringIsempty.isNullList(indentshop))
            map.put("img", "");
        else
            map.put("img", indentshop.get(0).get("img"));

        map.put("tag", 1);
        return map;
    }

    @Override
    public int updateAutoConfirmIndent() {
        long time = new Date().getTime();
        long recipienttime = time - 7 * 24 * 60 * 60 * 1000L;
        int tag = indentDao.updateAutoConfirmIndentByTime(recipienttime, time);
        Map<String, Object> indentinfo = indentDao.selectIndentinfoNotConfirmIndentByTime(recipienttime);
        if(indentinfo == null)
            RedisCash.redisString("confirmindenttime", (time + 7 * 24 * 60 * 60 * 1000L) + "");
        else
            RedisCash.redisString("confirmindenttime", (Long.parseLong(indentinfo.get("sendtime") + "") + 7 * 24 * 60 * 60 * 1000L) + "");
        return tag;
    }

    @Override
    public int updateAutoCancleIndent() {
        long time = new Date().getTime();
        long cancletime = time - 24 * 60 * 60 * 1000L;
        int tag = indentDao.updateAutoCancleIndentByTime(cancletime, time);
        Map<String, Object> indentinfo = indentDao.selectIndentinfoNotCancleIndentByTime(cancletime);
        if(indentinfo == null)
            RedisCash.redisString("cancleindenttime", (time + 24 * 60 * 60 * 1000L) + "");
        else
            RedisCash.redisString("cancleindenttime", (Long.parseLong(indentinfo.get("addtime") + "") + 24 * 60 * 60 * 1000L) + "");
        return 0;
    }


    /**
     * 获取微信预支付id
     *
     * @param indentnum 订单编号
     * @param reqip     请求ip
     * @param paymoney  支付金额
     * @param openid
     * @param indenttime
     * @param requrl
     * @return 微信预支付id
     */
    public static Map<String, Object> getWeChatPrepayId(String indentnum, String reqip, long paymoney, String openid, int indenttime, String requrl) {
        String tn;// 1 参数
        // 订单号
        String orderId = indentnum;// 生成订单编号
        // 附加数据 原样返回
        String attach = "";
        // 总金额以分为单位，不带小数点
        String totalFee = paymoney + "";

        // 订单生成的机器 IP
        // 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
        String notify_url = ConstantUtil.NOTIFY_URL;
        String trade_type = "JSAPI";

        // 商户号
        String mch_id = ConstantUtil.PARTNER;
        // 随机字符串
        String nonce_str = Sha1Util.getNonceStr();
        ;

        // 商品描述根据情况修改
        String body = "摘记";

        // 商户订单号
        String out_trade_no = orderId;

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", ConstantUtil.APP_ID);  //微信开发平台应用id
        packageParams.put("mch_id", mch_id);   //商户号
        packageParams.put("nonce_str", nonce_str);  //Sha1Util.getNonceStr();随机串
        packageParams.put("body", body);  //商品描述信息
        packageParams.put("attach", attach);  //附加数据
        packageParams.put("openid", openid);  //附加数据
        packageParams.put("out_trade_no", out_trade_no);  //自己生成订单号

        // 这里写的金额为1 分到时修改
        packageParams.put("total_fee", totalFee);  //支付总金额
        packageParams.put("spbill_create_ip", reqip);//订单生成的机器 IP
        packageParams.put("notify_url", notify_url);  //回调地址
        packageParams.put("trade_type", trade_type);  //app端（APP）还是pc端

        //packageParams.put("openid", openId);

        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(ConstantUtil.APP_ID, ConstantUtil.APP_SECRET, ConstantUtil.PARTNER_KEY);
        String sign = reqHandler.createSign(packageParams);
        String xml = "<xml>"
                + "<appid>" + ConstantUtil.APP_ID + "</appid>"
                + "<mch_id>" + mch_id + "</mch_id>"
                + "<nonce_str>" + nonce_str + "</nonce_str>"
                + "<sign>" + sign + "</sign>"
                + "<body><![CDATA[" + body + "]]></body>"
                + "<out_trade_no>" + out_trade_no + "</out_trade_no>"
                + "<attach>" + attach + "</attach>"
                + "<total_fee>" + totalFee + "</total_fee>"
                + "<spbill_create_ip>" + reqip + "</spbill_create_ip>"
                + "<notify_url>" + notify_url + "</notify_url>"
                + "<openid>" + openid + "</openid>"
                + "<trade_type>" + trade_type + "</trade_type>"
                + "</xml>";
        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        Map<String, Object> map =new GetWxOrderno().getPayNo(createOrderURL, xml);

        map.put("signbefore", sign);
        SortedMap<String, String> payMap = new TreeMap<String, String>();
        payMap.put("appId", ConstantUtil.APP_ID);
        payMap.put("timeStamp", indenttime + "");
        payMap.put("nonceStr", nonce_str);
        payMap.put("signType", "MD5");
        payMap.put("package", "prepay_id=" + map.get("prepay_id"));
        String resultsign = reqHandler.createSign(payMap);
        System.out.println(payMap);
        System.out.println("resultsign" + resultsign);
        map.put("result_sign", resultsign);
        map.put("nonceStr", nonce_str);
        return map;
    }

    /**
     * 获取订单总价格及运费信息
     *
     * @param shopinfo 商品信息
     * @param pid      省id
     * @param indentType
     * @param delType
     * @param uid
     * @return 订单总价格及运费
     */
    private Map<String, Object> getIndentInfo(JSONArray shopinfo, String pid, String indentType, int delType, String uid) {
        Map<String, Object> map = new HashMap<String, Object>();
        long totalmoney = 0;
        long freight = 0;
        long totalweight = 0;
        long favorable = 0;
        for (int i = 0; i < shopinfo.length(); i++) {
            try {
                // TODO: 2016/12/30 商品信息下架处理
                String shopid = shopinfo.getJSONObject(i).get("shopid") + "";
                long number = Long.parseLong(shopinfo.getJSONObject(i).get("num") + "");
                if (!shopinfo.getJSONObject(i).isNull("shopcartid") && delType == 1) {
                    String shopcartid = shopinfo.getJSONObject(i).get("shopcartid") + "";
                    if (!StringIsempty.isallempty(shopcartid)) {
                        int tag = shopDao.deleteShopCartInfo(shopcartid);
                    }
                }
//                String babysex = shopinfo.getJSONObject(i).get("babysex") + "";
//                String babyageid = shopinfo.getJSONObject(i).get("babyageid") + "";
                String shopspecpriceid = shopinfo.getJSONObject(i).get("shopspecid") + "";
                Map<String, Object> shop = shopDao.selectShopInfoById(shopid);
                if (StringIsempty.isNullMap(shop))
                    continue;
                Map<String, Object> shopspecprice = shopDao.selectShopSpecPriceById(shopspecpriceid);
                if (StringIsempty.isNullMap(shopspecprice))
                    continue;
                long price = 0;
                String usertype = ShopServiceImpl.getUserType(uid, userDao);
                if("1".equals(usertype))
                    price = Long.parseLong(shopspecprice.get("first") + "");
                else if("2".equals(usertype))
                    price = Long.parseLong(shopspecprice.get("second") + "");
                else if("3".equals(usertype))
                    price = Long.parseLong(shopspecprice.get("third") + "");
                else if("4".equals(usertype))
                    price = Long.parseLong(shopspecprice.get("forth") + "");
                else if("5".equals(usertype))
                    price = Long.parseLong(shopspecprice.get("fifth") + "");
                else
                    price = Long.parseLong(shopspecprice.get("price") + "");

                Map<String, Object> shopfavorable = new HashMap<String, Object>();
                shopfavorable.put("shopid", shopid);
                shopfavorable.put("number", number);
                Map<String, Object> shopfavorableinfo = shopDao.selectShopFavorabledByShopIdAndNum(shopfavorable);
                if (!StringIsempty.isNullMap(shopfavorableinfo)) {
                    favorable += price - price * Long.parseLong(shopfavorableinfo.get("lose") + "") / 100;
                    price *= Long.parseLong(shopfavorableinfo.get("lose") + "") / 100;
                }
                String shop_weight = shop.get("shop_weight") + "";
                totalweight += Long.parseLong(shop_weight) * number;
                if (!StringIsempty.isallempty(pid)) {
                    String freight_id = shop.get("freight_id") + "";
                    long shopweight = Long.parseLong(shop_weight) * number;
                    Map<String, Object> freightinfo = new HashMap<String, Object>();
                    freightinfo.put("freight_id", freight_id);
                    freightinfo.put("pid", " and pid =" + pid);
//                    Map<String, Object> freightmoney = systemDao.selectFreightMoneyByFreightId(freightinfo);
                    List<Map<String, Object>> freightmoney = systemDao.selectFreightMoneyByFreightId(freight_id);
                    if(!StringIsempty.isNullList(freightmoney)) {
                        boolean flag = false;
                        for (int j = 0; j < freightmoney.size(); j ++) {
                            if(flag)
                                continue;
                            Map<String, Object> freightmoneyinfo = freightmoney.get(j);
                            if(StringIsempty.isNullMap(freightmoneyinfo))
                                continue;
                            String pids = freightmoneyinfo.get("pid") + "";
                            String[] pidarray = pids.split(",");
                            if(pidarray != null && pidarray.length > 0) {
                                for (int k =0 ; k < pidarray.length; k ++) {
                                    if(flag)
                                        continue;
                                    if(pidarray[k].equals(pid)) {
                                        long money = Long.parseLong(freightmoneyinfo.get("money") + "");
                                        long weight = Long.parseLong(freightmoneyinfo.get("weight") + "");
                                        long weightprice = Long.parseLong(freightmoneyinfo.get("weightprice") + "");
                                        long shopfreight;
                                        if (weight >= shopweight)
                                            shopfreight = money;
                                        else
                                            shopfreight = money + (shopweight - weight) * weightprice;
                                        if (shopfreight > freight)
                                            freight = shopfreight;
                                        flag = true;
                                    }
                                }
                            }
                        }
                    }
                }
                totalmoney += price * number;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if("1".equals(indentType)) {
            map.put("totalmoney", totalmoney);
            map.put("freight", 0);
        } else {
            map.put("totalmoney", totalmoney + freight);
            map.put("freight", freight);
        }
        map.put("indentmoney", totalmoney);
        map.put("favorable", favorable);
        return map;
    }

    /**
     * 处理订单商品价格信息
     *
     * @param indentShop 订单商品信息
     */
    private void getIndentShopInfo(List<Map<String, Object>> indentShop) {
        for (int j = 0; j < indentShop.size(); j++) {
            Map<String, Object> indentshopinfo = indentShop.get(j);
            if (StringIsempty.isNullMap(indentshopinfo))
                continue;
            indentshopinfo.put("price", ValueJude.getDecima(indentshopinfo.get("price") + ""));
            indentShop.set(j, indentshopinfo);
        }
    }


    /**
     * 获取物流名称及物流单号
     *
     * @param indentinfo 订单信息
     * @param logistics  物流信息
     */
    private void getLogistics(Map<String, Object> indentinfo, Map<String, Object> logistics) {
        if (StringIsempty.isNullMap(logistics)) {
            indentinfo.put("logisticsname", "");
            indentinfo.put("logisticsnum", "");
        } else {
            indentinfo.put("logisticsname", logistics.get("logistics_name") + "");
            indentinfo.put("logisticsnum", logistics.get("logistics_num") + "");
        }
    }

    public static void main(String[] args) {
        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(ConstantUtil.APP_ID, ConstantUtil.APP_SECRET, ConstantUtil.PARTNER_KEY);
        SortedMap<String, String> payMap = new TreeMap<String, String>();
        payMap.put("appId", "wxcb6d3115c0924784");
        payMap.put("timeStamp", 1504060443 + "");
        payMap.put("nonceStr", "c11cb55c3d8dcc03a7ab7ab722703e0a");
        payMap.put("signType", "MD5");
        payMap.put("package", "prepay_id=wx2017083010340326346505ad0272607792");
        String resultsign = reqHandler.createSign(payMap);
        System.out.println(resultsign);
        //        System.out.println(getWeChatPrepayId(UtilDate.getOrderNum(),"112.11.12.54", 100, "oO38pwGqfDkjbIygMky3BtmibK6U", (int)new Date().getTime() / 1000, ""));
    }

   //{appId=wxcb6d3115c0924784, nonceStr=c11cb55c3d8dcc03a7ab7ab722703e0a, package=prepay_id=wx2017083010340326346505ad0272607792, signType=MD5, timeStamp=1504060443}

}